<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/14 17:33
 */

namespace App\Http\Controllers;

use App\Http\Models\User;
use Auth;
use DB;
use Illuminate\Http\Request;
use App\Http\Models\UserAuth;
use App\Http\Models\UserNameLog;
use App\Http\Models\UserKillStatus;
use App\Http\Models\Region;
use Validator;
use Illuminate\Support\Facades\Cache;

class UserAuthController extends Controller
{
    protected $user_income = [
        ["income_type" => UserAuth::USER_INCOME_ONE, "income" => '1--5W'],
        ["income_type" => UserAuth::USER_INCOME_TWO, "income" => '5--10W'],
        ["income_type" => UserAuth::USER_INCOME_THREE, "income" => '10--50W'],
        ["income_type" => UserAuth::USER_INCOME_FOUR, "income" => '50--100W'],
        ["income_type" => UserAuth::USER_INCOME_FIVE, "income" => '100W以上'],
    ];


    /**
     * 获取用户认证状态
     * @return string
     */
    public function getUserAuth()
    {
        $userId = Auth::id();
        $userAuthInfo = UserAuth::where('user_id', $userId)->first();
        if (empty($userAuthInfo)) {
            return json_encode(['code' => 1, 'msg' => '暂未提交认证信息', 'data' => ['userIncomeList' => $this->user_income]]);
        } else {
            if ($userAuthInfo->status == 1) {
                return json_encode(['code' => 0, 'msg' => '认证审核通过', 'data' => ['userIncomeList' => $this->user_income, 'userAuthInfo' => $userAuthInfo]]);
            } elseif ($userAuthInfo->status == 0) {
                return json_encode(['code' => 2, 'msg' => '认证审核中', 'data' => ['userIncomeList' => $this->user_income, 'userAuthInfo' => $userAuthInfo]]);
            } else {
                return json_encode(['code' => 3, 'msg' => '认证审核被拒', 'data' => ['userIncomeList' => $this->user_income, 'userAuthInfo' => $userAuthInfo]]);
            }
        }
    }

    /**
     * 用户认证数据提交
     * @param Request $request
     * @return string
     */
    public function addUserAuth(Request $request)
    {
        $data = $request->only(['real_name', 'id_number', 'id_image_just', 'id_image_back', 'user_income', 'income_prove', 'channel_info', 'channel_prove', 'phone']);

        $validator = Validator::make($data, [
            'real_name' => 'required|max:8|min:2',
            'id_number' => 'required',
            'id_image_just' => 'required',
            'id_image_back' => 'required',
            'user_income' => 'required|between:1,5',
            'channel_info' => 'required|string',
            'income_prove' => 'required|string',
            'channel_prove' => 'required|string',
            'phone' => 'required|regex:/^1[34578]{1}\d{9}$/',
        ]);

        $error = [];
        if ($validator->fails()) {
            $error_info = json_decode(json_encode($validator->errors(), true));
            foreach ($error_info as $key => $value) {
                $error[] = $value[0];
            }
        }
        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error[0], 'data' => '']);
        }

        if (isset($data['id_number']) && !preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $data['id_number'])) {
            return json_encode(['code' => 1, 'msg' => '身份证号码有误', 'data' => '']);
        }
        $data['deleted_at'] = null;
        $data['status'] = 0;
        $bool = UserAuth::updateOrCreate(['user_id' => Auth::id()], $data);
        if ($bool) {
            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => 'ng', 'data' => '']);
        }
    }

    /**
     * 个人信息修改
     */
    public function userEditInfo(Request $request)
    {
        $data = $request->only(['name', 'signature', 'city_id', 'province_id', 'area_id', 'qq', 'income_prove']);
        $validator = Validator::make($data, [
            'name' => 'required|max:8|min:2',
            'signature' => 'required|max:40',
            'city_id' => 'required|numeric',
            'province_id' => 'required|numeric',
            'area_id' => 'required|numeric',
            'qq' => 'required|numeric',
            'income_prove' => 'required',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error[0], 'data' => '']);
        }
        $nameLog = UserNameLog::where(['user_id' => Auth::id()])->count();
        if ($nameLog >= 2) {
            return json_encode(['code' => 1, 'msg' => '昵称只能修改两次!', 'data' => '']);
        }
        $user = User::where('id', Auth::id())->first();
        $user->name = $data['name'];
        $user->signature = $data['signature'];
        $user->income_prove = $data['income_prove'];
        $user->city_id = $data['city_id'];
        $user->province_id = $data['province_id'];
        $user->area_id = $data['area_id'];
        $user->qq = $data['qq'];
        $bool = $user->save();
        if ($bool) {
            UserNameLog::create(['user_id' => Auth::id(), 'name' => $data['name']]);
            return json_encode(['code' => 0, 'msg' => '资料修改成功!', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => '资料修改失败!', 'data' => '']);
        }
    }

    /**
     * 进行编辑用户的头像信息,并保存
     * @param Request $request
     * @return string
     */
    public function userEditAvatar(Request $request)
    {
        $data = $request->only(['avatar']);
        $validator = Validator::make($data, [
            'avatar' => 'required|url',
        ]);
        $error = $this->ErrorInfo($validator);
        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error[0], 'data' => '']);
        }
        $user = User::where('id', Auth::id())->first();
        $user->avatar = $data['avatar'];
        $bool = $user->save();
        if ($bool) {
            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => 'ng', 'data' => '']);
        }
    }

    /**
     * 捕获validate的erroer数据
     * @param $validator
     * @return string
     */

    protected function ErrorInfo($validator)
    {

        $error = [];
        if ($validator->fails()) {
            $error_info = json_decode(json_encode($validator->errors(), true));
            foreach ($error_info as $key => $value) {
                $error[] = $value[0];
            }
        }
        return $error;
    }

    /**
     * 验证数组的url是否符合图片地址的格式
     * @param $data array
     * @return array
     */
    protected function ImageUrlValidate($data)
    {
        $error = [];
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (!preg_match("/(http:\/\/)?\w+\.(jpg|jpeg|gif|png)/", $value)) {
                    $error[] = $key . '图片url地址有误';
                }
            }
        }
        return $error;
    }


}